import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  Keyboard,
  RefreshControl,
  FlatList,
  ActivityIndicator,
  TouchableWithoutFeedback,
  Modal,
  Linking,
  ScrollView,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {
  TextButton,
  LinearButton,
  LinearBoardButton,
} from '../../components/Button';
import {LinerBoardTextInput} from '../../components/TextInput';
import {NormalHeader} from '../../components/NavigationHeader';
import {showToast} from '../../components/Toast';
import {userLogout} from '../../redux/action';
import Clipboard from '@react-native-community/clipboard';
import PriceCell from './components/PriceCell';
import moment from 'moment';
import {queryWalltBalance} from '../../redux/action/index';
import {formatLeftTime, subNumerString} from '../../utils/tools';
import {
  queryAuctionDetail,
  queryAuctionOffer,
  queryAuctionEvents,
} from '../../api/auction';
import {BASE_API} from '../../config';
import ModalHandler from '../../components/ModalHandler';
import BigNumber from 'bignumber.js';
import ChainUtils from '../../utils/chain/ChainUtils';
import WalletUtils from '../../utils/wallet/WalletUtils';
import {CachedImage} from 'react-native-img-cache';
import WalletConnectModal from '../../components/WalletConnectModal';

class Auction extends BaseComponent {
  constructor(props) {
    super(props);

    let auction = props.navigation.state.params.auction;
    let timeSpace = new Date(auction.expireDate * 1000) - new Date().valueOf();

    this.state = {
      scollEnabled: false,
      isRefreshing: false,
      auctionRefreshing: false,
      isLoadMore: false,
      modalVisible: false,
      loading: false,
      success: false,
      password: '',
      page: 1,
      size: 10,
      total: 0,
      showHistory: true,
      gasUsed: 0,
      auction: {
        ...auction,
        leftTime:
          formatLeftTime(timeSpace) +
          `(${moment(auction.expireDate * 1000).format(
            'YYYY-MM-DD HH:mm:ss',
          )})`,
        user: {},
        item: {},
      },
      prices: [],
      historys: [],
      showWalletConnect: false,
      tx: undefined,
    };
  }

  componentDidMount() {
    this.onRefresh();
  }

  formatPrice = (price, payCoinDecimal) => {
    price = new BigNumber(price);
    const decimal = new BigNumber(Math.pow(10, payCoinDecimal));
    let vAmount = parseFloat(price.dividedBy(decimal));

    let prettyPrice = ChainUtils.subStringNum(vAmount, 8);
    return prettyPrice;
  };

  initData = () => {
    queryAuctionDetail({
      userToken: this.props.userInfo.token,
      auctionId: this.state.auction.auctionId,
    })
      .then((res) => {
        console.log('================ Auction');
        console.log(res);

        let timeSpace =
          new Date(res.data.expireDate * 1000) - new Date().valueOf();

        this.setState({
          auctionRefreshing: false,
          auction: {
            ...res.data,
            img: res.data.img,
            leftTime:
              formatLeftTime(timeSpace) +
              `(${moment(res.data.expireDate * 1000).format(
                'YYYY-MM-DD HH:mm:ss',
              )})`,
          },
        });
      })
      .catch((err) => {
        console.log(err);
        showToast(err.msg || 'query auction detail failed');
      });

    queryAuctionEvents({auctionId: this.state.auction.auctionId})
      .then((res) => {
        console.log('查询历史记录');
        console.log(res);
        this.setState({
          historys: res.data,
        });
      })
      .catch((err) => {
        console.log(err);
        showToast(err.msg || 'query auction events failed');
      });
  };

  _renderEmptyView = () => (
    <View
      style={{
        //   backgroundColor: 'yellow',
        width: '100%',
        height: 200,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Image
        style={{width: 95}}
        source={require('../../assets/browser/empty.png')}></Image>
      <Text style={{color: 'black', padding: 20, alignSelf: 'center'}}>
        No offers yet
      </Text>
    </View>
  );

  _renderItemSeparatorComponent = () => (
    <View
      style={{height: 1, backgroundColor: 'rgba(151,151,151,0.5)', margin: 10}}
    />
  );

  _renderItem = (item) => (
    <PriceCell
      price={item.item}
      onPressAccept={() => this._onPressBuyButton(item.item)}
      onPressReject={() => this._onRejectOffer(item.item)}
    />
  );

  _onRejectOffer = async (item) => {
    this.handleShowWalletConnectSignRejectBid();
    return;
    WalletUtils.getCreateAuctionGasPrice()
      .then((res) => {
        this.setState({
          gasUsed: res,
          modalVisible: true,
        });
      })
      .catch((err) => {
        console.log('获取失败');
      });
  };

  _onPressBuyButton = async (item) => {
    console.log('点击购买按钮');
    this.props.navigation.navigate('Accept', {
      offer: item,
      auction: this.state.auction,
      refresh: () => {
        this.initData();
      },
    });
  };

  onRefresh = async () => {
    console.log('刷新数据');

    this.setState(
      {
        auctionRefreshing: true,
        page: 1,
      },
      async () => {
        //更新商品信息
        this.initData();
        await this.getList();
        this.setState({
          auctionRefreshing: false,
        });
      },
    );
  };

  ListFooterComponent = () => {
    let showLoadingMore = this.state.total > this.state.page * this.state.size;
    return this.state.prices.length == 0 ? null : (
      <View>
        <View
          style={{
            flexDirection: 'row',
            color: '#fff',
            justifyContent: 'center',
          }}>
          {showLoadingMore ? (
            <ActivityIndicator size="small" animating={true} />
          ) : null}
          <Text style={{color: '#fff'}}>
            {showLoadingMore ? 'loading more...' : 'no more data'}
          </Text>
        </View>
      </View>
    );
  };

  onEndReached() {
    console.log('>>上拉加载>>>');
    const {page, isLoadMore, total, prices} = this.state;
    console.log('当前列表数量' + prices.length);
    console.log(total);
    if (prices.length < total) {
      this.setState(
        {
          page: page + 1,
          isLoadMore: true,
        },
        () => {
          this.getList();
        },
      );
    } else {
      console.log('不需要刷新数据');
      this.setState({
        isLoadMore: false,
      });
    }
  }

  getList = async () => {
    let {page, size, auction} = this.state;

    console.log(this.state.auction);

    try {
      let res = await queryAuctionOffer({
        userToken: this.props.userInfo.token,
        auctionId: auction.auctionId,
        page,
        size,
      });
      console.log('竞拍offer');
      console.log(res);

      var newPrices = res.data.rows.map((item) => {
        return {
          ...item,
          userImg: BASE_API + item.userImg,
          time: moment(item.creteTime).format('YYYY-MM-DD hh:mm:ss'),
        };
      });

      if (page !== 1) {
        newPrices = this.state.prices.concat(newPrices);
      }

      console.log(newPrices);

      this.setState({
        prices: [...newPrices],
        total: res.data.pageInfo.total,
      });
    } catch (err) {
      console.log('查询出错');
      console.log(err);
    }
  };

  onPressBackground = () => {
    if (this.state.loading) {
      return;
    }

    this.setState({
      modalVisible: false,
      loading: false,
    });
  };

  priceDrop = async () => {
    let firstPrice = this.state.prices.length > 0 ? this.state.prices[0] : null;
    console.log(firstPrice);

    if (
      firstPrice &&
      firstPrice.bidAddress.toLowerCase() ==
        this.props.userInfo.metamaskAddress.toLowerCase()
    ) {
      this._showAlert({content: 'Your bid price is the highest'});
      return;
    }

    this.props.navigation.navigate('PriceBid', {
      auction: this.state.auction,
      refresh: () => {
        console.log('刷新价格列表');
        this.onRefresh();
      },
    });
  };

  renderEventItem = (item) => {
    let {name, hash, createTime} = item.item;
    return (
      <View
        style={{
          backgroundColor: item.index % 2 == 0 ? '#E9E9E9' : 'white',
          width: '100%',
          height: 40,
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}>
        <Text
          numberOfLines={3}
          ellipsizeMode="tail"
          style={{
            color: '#525252',
            width: 80,
            textAlign: 'left',
            marginLeft: 20,
          }}>
          {name}
        </Text>
        <TouchableOpacity
          style={{paddingLeft: 10, flex: 1}}
          onPress={() => {
            let url = this.props.chainConfig.explorer + '/tx/' + hash;
            Linking.canOpenURL(url)
              .then((supported) => {
                if (!supported) {
                  console.warn("Can't handle url: " + url);
                } else {
                  return Linking.openURL(url);
                }
              })
              .catch((err) => console.error('An error occurred', url));
          }}
          activeOpacity={0.8}>
          <Text
            numberOfLines={1}
            ellipsizeMode="middle"
            style={{
              color: '#525252',
              textAlign: 'center',
              textDecorationLine: 'underline',
            }}>
            {hash}
          </Text>
        </TouchableOpacity>
        <Text
          style={{
            color: '#525252',
            width: 90,
            textAlign: 'right',
            marginRight: 20,
          }}>
          {createTime}
        </Text>
      </View>
    );
  };

  rejectOffer = () => {
    Keyboard.dismiss();
    this.setState(
      {
        loading: true,
      },
      async () => {
        console.log(this.state.password);

        try {
          var privateKey = await WalletUtils.privateKeyOfKeystore(
            this.props.userInfo.keystore,
            this.state.password,
          );
        } catch (err) {
          console.log('错误' + err);
          this.setState(
            {
              modalVisible: false,
              loading: false,
            },
            () => {
              this._showAlert({content: 'invalid password'});
            },
          );
          return;
        }

        console.log(this.props.signinNFT);

        let {nftAddress, tokenId} = this.props.navigation.state.params.auction;

        WalletUtils.rejectPrice(
          privateKey,
          this.props.proxy.address,
          nftAddress,
          tokenId,
          (hash) => {
            this.setState({
              result: '交易已发送，正在监听交易->' + hash,
            });
          },
        )
          .then(async (res) => {
            console.log(res);

            this.setState(
              {
                loading: false,
                modalVisible: false,
              },
              () => {
                this.onRefresh();
              },
            );
          })
          .catch((err) => {
            this.setState(
              {
                modalVisible: false,
                loading: false,
              },
              () => {
                this._showAlert({content: err + ''});
              },
            );
          });
      },
    );
  };

  onPressWalletBackground = () => {
    this.setState({
      showWalletConnect: false,
    });
  };

  resultCall = (hash, err) => {
    if (err) {
      this.setState(
        {
          showWalletConnect: false,
        },
        () => {
          this._showAlert({content: err});
        },
      );
      return;
    }
    console.log('收到交易的HASH回调');
    console.log(hash);

    this.setState({
      showWalletConnect: false,
      modalVisible: true,
      loading: true,
    });

    WalletUtils.listenTx(hash)
      .then((res) => {
        console.log('交易已上链' + res);
        this.setState(
          {
            loading: false,
            modalVisible: false,
          },
          () => {
            this.onRefresh();
          },
        );
      })
      .catch((err) => {
        console.log('交易失败');
        this.setState(
          {
            modalVisible: false,
            loading: false,
          },
          () => {
            this._showAlert({content: err?.message || err + ''});
          },
        );
      });
  };

  handleShowWalletConnectSignRejectBid = async () => {
    //生成交易
    this._showLoading();
    try {
      let {nftAddress, tokenId} = this.props.navigation.state.params.auction;

      let tx = await WalletUtils.getRejectPriceTx(
        this.props.proxy.address,
        nftAddress,
        tokenId,
        this.props.userInfo.metamaskAddress,
      );
      console.log('待签名的交易：');
      console.log(tx);
      this._hideLoading();
      //跳转
      this.setState({
        showWalletConnect: true,
        tx,
      });
    } catch (err) {
      this._hideLoading();
      this._showAlert({content: err?.msg || err + ''});
    }
  };

  _handlerView = () => {
    let {payCoin} = this.props.navigation.state.params.auction;
    let {canBid, needApprove, amount} = this.state;

    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            fontWeight: 'bold',
            marginTop: 20,
            marginBottom: 30,
            color: '#6701F4',
          }}>
          Send a transaction to reject the offer.
        </Text>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            marginBottom: 20,
            height: 30,
            borderRadius: 15,
            backgroundColor: '#571DAA',
            alignItems: 'center',
            justifyContent: 'space-between',
            paddingLeft: 20,
            paddingRight: 20,
          }}>
          <Text style={{color: 'white'}}>Gas Fee</Text>
          <Text
            style={{
              color: 'white',
            }}>{`${this.state.gasUsed}${this.props.gasSymbol}`}</Text>
        </View>
        <LinerBoardTextInput
          style={{
            width: '100%',
            padding: 0,
            height: 44,
          }}
          defaultValue={this.state.password}
          secureTextEntry={true}
          onChangeText={(text) => {
            this.setState({
              password: text,
            });
          }}
          placeholder="Your wallet password"></LinerBoardTextInput>
        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            justifyContent: 'flex-end',
            marginBottom: 30,
          }}>
          <LinearBoardButton
            buttonStyle={{
              width: 100,
              height: 30,
              marginRight: 20,
            }}
            onPress={() => {
              this.setState({
                modalVisible: false,
              });
            }}
            text={'Cancel'}></LinearBoardButton>
          <LinearButton
            buttonStyle={{
              width: 100,
              height: 30,
            }}
            onPress={this.rejectOffer}
            text={'Confirm'}></LinearButton>
        </View>
      </View>
    );
  };

  renderComponent = () => {
    let {
      auction,
      prices,
      modalVisible,
      loading,
      success,
      historys,
      showWalletConnect,
      tx,
    } = this.state;
    let {userInfo} = this.props;
    let {
      img,
      name,
      leftTime,
      startPrice,
      user,
      payCoin,
      bidValue,
      payCoinDecimal,
      maxPrice,
      dealPrice,
      status,
      userId,
      holder,
    } = auction;

    //处理精度
    bidValue = this.formatPrice(bidValue, payCoinDecimal);
    startPrice = this.formatPrice(startPrice, payCoinDecimal);
    maxPrice = this.formatPrice(maxPrice, payCoinDecimal);
    dealPrice = this.formatPrice(dealPrice, payCoinDecimal);

    let firstPrice =
      this.state.prices.length > 0 ? this.state.prices[0] : {bidAddress: ''};

    let priceDropValid =
      firstPrice?.bidAddress.toLowerCase() !=
      userInfo.metamaskAddress.toLowerCase();

    // let gasCoin = this.props.coins.filter((item) => {
    //   return item.symbol == this.props.gasSymbol;
    // })[0];

    let newPrices = prices.map((item, idx) => {
      return {
        ...item,
        value: this.formatPrice(item.value, item.payCoinDecimal),
        showAcceptButton:
          idx == 0 &&
          userInfo.metamaskAddress.toLowerCase() == holder.toLowerCase(),
        showRejectButton:
          idx == 0 &&
          status == 1 &&
          userInfo.metamaskAddress.toLowerCase() == holder.toLowerCase(),
      };
    });

    return (
      <View style={{flex: 1, backgroundColor: '#160231'}}>
        <NormalHeader
          navigation={this.props.navigation}
          text="Auction"
          left={{
            icon: require('../../assets/common/common_back_white.png'),
            onPress: () => {
              Keyboard.dismiss();
              this.props.navigation.goBack();
            },
          }}
        />
        <ScrollView
          refreshControl={
            <RefreshControl
              refreshing={this.state.auctionRefreshing}
              onRefresh={this.onRefresh}
              tintColor={'white'}
              titleColor={'white'}
              title="Loading..."
            />
          }
          style={{paddingLeft: 20, paddingRight: 20, paddingTop: 20, flex: 1}}>
          <View
            style={{
              width: '100%',
              height: 110,
              borderRadius: 14,
              borderBottomLeftRadius: 10,
              borderBottomRightRadius: 10,
              backgroundColor: 'white',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
            <CachedImage
              style={{
                width: 80,
                height: 80,
                borderRadius: 10,
                backgroundColor: 'lightGray',
                marginLeft: 15,
                marginRight: 10,
              }}
              source={{uri: img}}
            />
            <View
              style={{
                flex: 1,
                justifyContent: 'center',
              }}>
              <Text
                numberOfLines={2}
                ellipsizeMode="tail"
                style={{
                  paddingBottom: 0,
                  fontWeight: 'bold',
                  fontSize: 20,
                  color: '#7204F4',
                }}>
                {name}
              </Text>
              <View
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                }}>
                <Text style={{color: '#8B8B8B'}}>Owner by</Text>
                <TouchableOpacity
                  onPress={() => {
                    this.props.navigation.navigate('MyAuctions', {
                      address: auction.holder,
                      refreshAuction: (item) => {
                        let timeSpace =
                          new Date(auction.expireDate * 1000) -
                          new Date().valueOf();

                        this.setState({
                          auction: {
                            ...item,
                            user: {},
                            item: {},
                          },
                        });

                        this.onRefresh();
                      },
                    });
                  }}>
                  <Text
                    numberOfLines={1}
                    style={{
                      paddingLeft: 0,
                      color: '#7204F4',
                      marginRight: 80,
                      height: 20,
                    }}>
                    {auction.holder}
                  </Text>
                </TouchableOpacity>
              </View>
              <TouchableOpacity
                style={{
                  marginTop: 5,
                  borderRadius: 8,
                  height: 16,
                  backgroundColor: '#571DAA',
                  width: 100,
                }}
                onPress={() => {
                  console.log(this.state.auction);
                  this.props.navigation.navigate('NftDetail', {
                    nft: this.state.auction.item,
                  });
                }}>
                <Text
                  style={{
                    paddingLeft: 0,
                    color: 'white',
                    textAlign: 'center',
                    lineHeight: 16,
                    fontSize: 12,
                  }}>
                  {'more detail >'}
                </Text>
              </TouchableOpacity>
            </View>
            {/* <LinearButton
              onPress={() => {
                console.log(this.state.auction);
                this.props.navigation.navigate('NftDetail', {
                  nft: this.state.auction.item,
                });
              }}
              buttonStyle={{
                width: 100,
                height: 35,
                marginRight: 20,
                marginBottom: 20,
              }}
              text="Detail"
            /> */}
          </View>
          <View
            style={{
              width: '100%',
              height: 110,
              borderRadius: 14,
              borderTopLeftRadius: 10,
              borderTopRightRadius: 10,
              backgroundColor: 'white',
              justifyContent: 'space-between',
            }}>
            <View
              style={{
                height: 2,
                marginLeft: 4,
                marginRight: 4,
                marginTop: -1,
              }}>
              <Image
                style={{
                  height: 2,
                  width: '100%',
                }}
                source={require('../../assets/auction/line.png')}></Image>
            </View>
            <View style={{flexDirection: 'row', alignItems: 'flex-end'}}>
              <Text
                style={{
                  color: '#6C03F4',
                  marginTop: 10,
                  marginLeft: 20,
                  width: 90,
                }}>
                {status == 0
                  ? bidValue == 0
                    ? 'Minimum Bid'
                    : 'Last Price'
                  : 'Current Bid'}
                :
              </Text>
              <Text
                style={{
                  marginLeft: 0,
                  marginRight: 5,
                  marginBottom: -3,
                  color: '#6C03F4',
                  fontSize: 24,
                  fontWeight: 'bold',
                }}>
                {bidValue == 0 ? startPrice : bidValue}
              </Text>
              <Text
                style={{
                  color: '#6C03F4',
                  fontSize: 12,
                  fontWeight: 'bold',
                }}>
                {payCoin}
              </Text>
            </View>
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'flex-end',
                marginTop: -5,
              }}>
              <Text
                style={{
                  color: '#6C03F4',
                  marginTop: 10,
                  marginLeft: 20,
                  width: 90,
                }}>
                {status == 0 ? 'Offer Price:' : 'Deal Price:'}
              </Text>
              <Text
                style={{
                  marginLeft: 0,
                  marginRight: 5,
                  marginBottom: -3,
                  color: '#6C03F4',
                  fontSize: 24,
                  fontWeight: 'bold',
                }}>
                {status == 0 ? maxPrice : dealPrice}
              </Text>
              <Text
                style={{
                  color: '#6C03F4',
                  fontSize: 12,
                  fontWeight: 'bold',
                }}>
                {payCoin}
              </Text>
            </View>
            <View
              style={{
                height: 28,
                width: '100%',
                borderRadius: 14,
                backgroundColor: '#571DAA',
                justifyContent: 'center',
                paddingLeft: 20,
              }}>
              <Text style={{color: 'white', fontSize: 12}}>
                {auction.status != 0
                  ? 'The auction is Finished'
                  : 'The auction ends in ' + leftTime}
              </Text>
            </View>
            {bidValue == 0 ? (
              <Image
                style={{position: 'absolute', right: 20, top: -12}}
                source={require(`../../assets/home/auc_min.png`)}></Image>
            ) : (
              <Image
                style={{position: 'absolute', right: 20, top: -12}}
                source={require(`../../assets/home/auc_top.png`)}></Image>
            )}
          </View>
          <View
            style={{
              maxHeight: 300,
              backgroundColor: 'white',
              borderRadius: 14,
              marginTop: 20,
              position: 'relative',
            }}>
            <Image
              style={{position: 'absolute', right: 20, top: -9}}
              source={require('../../assets/home/offers.png')}></Image>
            <Text
              style={{
                width: '100%',
                height: 30,
                lineHeight: 30,
                color: '#7204F4',
                marginLeft: 20,
                marginTop: 10,
              }}>
              Offers
            </Text>
            <FlatList
              style={{marginBottom: 0, maxHeight: 300}}
              data={newPrices}
              keyExtractor={(item, index) => item.price} // 给定的item生成一个不重复的key
              renderItem={this._renderItem}
              ListEmptyComponent={this._renderEmptyView}
              ItemSeparatorComponent={this._renderItemSeparatorComponent}
              ListFooterComponent={this.ListFooterComponent}
              onEndReached={() => this.onEndReached()}
              onEndReachedThreshold={0.2}
              contentContainerStyle={{flexGrow: 1}}
              ListFooterComponentStyle={{flex: 1, justifyContent: 'flex-end'}}
              // refreshControl={
              //   <RefreshControl
              //     // tintColor="black"
              //     refreshing={this.state.isRefreshing}
              //     onRefresh={this.onRefresh}
              //     colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
              //     progressBackgroundColor="#ffffff"
              //   />
              // }
            />
          </View>
          <View
            style={{
              marginTop: 20,
              borderRadius: 22,
              marginBottom: 20,
            }}>
            <TouchableWithoutFeedback
              onPress={() => {
                this.setState({
                  showHistory: !this.state.showHistory,
                });
              }}>
              <View
                style={{
                  flex: 1,
                  height: 40,
                  backgroundColor: '#571DAA',
                  borderRadius: 20,
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}>
                <Text
                  style={{
                    flex: 1,
                    marginLeft: 20,
                    color: 'white',
                    fontWeight: 'bold',
                  }}>
                  Trading History
                </Text>
                <Image
                  style={{marginRight: 20}}
                  source={
                    this.state.showHistory
                      ? require('../../assets/room/up.png')
                      : require('../../assets/room/down.png')
                  }
                />
              </View>
            </TouchableWithoutFeedback>
            {this.state.showHistory ? (
              <View
                style={{
                  width: '100%',
                  borderRadius: 20,
                  backgroundColor: 'white',
                  paddingTop: 20,
                  paddingBottom: 20,
                  marginBottom: 20,
                }}>
                <View
                  style={{
                    flexDirection: 'row',
                    width: '100%',
                    justifyContent: 'space-between',
                    marginBottom: 20,
                  }}>
                  <Text
                    style={{
                      color: '#6A02F4',
                      flex: 1,
                      textAlign: 'left',
                      marginLeft: 20,
                    }}>
                    Event
                  </Text>
                  <Text
                    style={{color: '#6A02F4', flex: 1, textAlign: 'center'}}>
                    Hash
                  </Text>
                  <Text
                    style={{
                      color: '#6A02F4',
                      flex: 1,
                      textAlign: 'right',
                      marginRight: 20,
                    }}>
                    Date
                  </Text>
                </View>
                <FlatList
                  style={{
                    maxHeight: 300,
                    width: '100%',
                  }}
                  data={historys}
                  keyExtractor={(item, index) => item.eventId} // 给定的item生成一个不重复的key
                  renderItem={this.renderEventItem}
                />
              </View>
            ) : null}
          </View>
          <View
            style={{
              height: 120,
              flexDirection: 'row',
              paddingLeft: 50,
              paddingRight: 50,
              justifyContent: 'space-around',
            }}>
            {auction.holder &&
            auction.holder.toLowerCase() ==
              userInfo.metamaskAddress.toLowerCase() ? null : (
              <LinearButton
                onPress={this.priceDrop}
                isDisabled={!priceDropValid}
                text={'Place Bid'}
                buttonStyle={{width: 180}}
              />
            )}
          </View>
          <View
            style={{
              width: '100%',
              height: this.props.widgetLayout.show
                ? this.props.widgetLayout.height
                : 0,
              marginTop: 10,
            }}></View>
        </ScrollView>
        <ModalHandler
          visible={modalVisible}
          loading={loading}
          success={success}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
        <WalletConnectModal
          visible={showWalletConnect}
          resultCall={this.resultCall}
          onPressBackground={this.onPressWalletBackground}
          tx={tx}></WalletConnectModal>
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  coins: state.Chain.coins,
  gasSymbol: state.Chain.gasSymbol,
  proxy: state.Chain.proxy,
  chainConfig: state.Chain.config,
  widgetLayout: state.Layout.widgetLayout,
});

const mapDispatchToProps = (dispatch) => ({
  queryWalltBalance: () => dispatch(queryWalltBalance()),
});

export default connect(mapStateToProps, mapDispatchToProps)(Auction);
